1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.io;
18
19 import com.google.common.base.Preconditions;
20
21 import java.io.IOException;
22 import java.io.Reader;
23 import java.util.Iterator;
24
25 import javax.annotation.Nullable;
26
27
28
29
30
31
32
33 class MultiReader extends Reader {
34 private final Iterator<? extends CharSource> it;
35 private Reader current;
36
37 MultiReader(Iterator<? extends CharSource> readers) throws IOException {
38 this.it = readers;
39 advance();
40 }
41
42
43
44
45 private void advance() throws IOException {
46 close();
47 if (it.hasNext()) {
48 current = it.next().openStream();
49 }
50 }
51
52 @Override public int read(@Nullable char cbuf[], int off, int len) throws IOException {
53 if (current == null) {
54 return -1;
55 }
56 int result = current.read(cbuf, off, len);
57 if (result == -1) {
58 advance();
59 return read(cbuf, off, len);
60 }
61 return result;
62 }
63
64 @Override public long skip(long n) throws IOException {
65 Preconditions.checkArgument(n >= 0, "n is negative");
66 if (n > 0) {
67 while (current != null) {
68 long result = current.skip(n);
69 if (result > 0) {
70 return result;
71 }
72 advance();
73 }
74 }
75 return 0;
76 }
77
78 @Override public boolean ready() throws IOException {
79 return (current != null) && current.ready();
80 }
81
82 @Override public void close() throws IOException {
83 if (current != null) {
84 try {
85 current.close();
86 } finally {
87 current = null;
88 }
89 }
90 }
91 }